#include "CameraWorker.h"
#include <QImage>
#include <QDebug>

CameraWorker::CameraWorker(int id, QMutex *m, QWaitCondition *t, QObject *parent)
    : QObject(parent), m_cameraId(id), m_mutex(m), m_trigger(t)
{}
void CameraWorker::stop() { m_running = false; m_trigger->wakeAll(); }

void CameraWorker::capture()
{
    cv::VideoCapture cap(m_cameraId);
    if (!cap.isOpened()) {
        qWarning() << "Camera" << m_cameraId << "open failed";
        emit finished();
        return;
    }
    while (m_running) {
        m_mutex->lock();
        m_trigger->wait(m_mutex);
        m_mutex->unlock();
        if (!m_running) break;
        cv::Mat frame;
        cap >> frame;
        if (frame.empty()) continue;
        cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
        QImage img(frame.data, frame.cols, frame.rows,
                   static_cast<int>(frame.step), QImage::Format_RGB888);
        emit frameReady(img.copy());
    }
    emit finished();
}
